package com.mp.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * @author jack
 */
@Component
public class NettyServer {

    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap server;

    private ChannelFuture future;

    private static class SingletionWSServer {
        static final NettyServer INSTANCE = new NettyServer();
    }

    public static NettyServer getInstance() {
        return SingletionWSServer.INSTANCE;
    }

    public NettyServer() {
        // 1. NioEventLoopGroup 异步事件循环组
        // 1.1 selector监听client发起的OP_ACCEPT,
        //     接收client连接,转发给workerGroup
        mainGroup = new NioEventLoopGroup();
        // 1.2 selector监听client发起的OP_READ，
        //     对client请求处理
        subGroup = new NioEventLoopGroup();
        // 2. 服务端启动配置
        server = new ServerBootstrap();

        server
                // 实现
                .group(mainGroup, subGroup)
                // 反射创建nio类型的channel
                .channel(NioServerSocketChannel.class)
                // 设置通道初始化,子处理器 - workerGroup
                .childHandler(new NettyServerInitializer());
    }

    public void start() {
        // 绑定Server端口,启动服务
        // bind操作: init和register
        this.future = server.bind(8088);
        System.err.println("netty websocket server start");
    }

}
